package com.yugu.park.security.handle;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.ui.ModelMap;
import com.alibaba.fastjson.JSON;
import com.yugu.park.config.TokenService;
import com.yugu.enums.HttpCode;
import com.yugu.park.security.entity.LoginUser;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;

@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

	@Autowired
	private TokenService tokenService;

	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {

		LoginUser loginUser = tokenService.getLoginUser(request);
		if (ObjectUtil.isNotNull(loginUser)) {
//			String userName = loginUser.getUsername();
			// 删除用户缓存记录
			tokenService.delLoginUser(loginUser.getToken());
			// 记录用户退出日志
//			AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
		}
		ModelMap map = new ModelMap();
        map.put("httpCode", HttpCode.OK.value());
        map.put("msg", "退出成功");
		ServletUtil.write(response, JSON.toJSONString(map), "application/json;charset=UTF-8");
	}

}
